package com.scalar.chiptrack.finance.openpo.actioncommands;

import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackExtendedAction;

import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.users.ErrorReport;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.finance.openpo.forms.OpenPurchaseOrderForm;
import com.scalar.chiptrack.finance.openpo.forms.PurchaseOrderForm;
import com.scalar.chiptrack.finance.openpo.forms.PurchaseOrderReceiptForm;
import com.scalar.chiptrack.finance.openpo.PurchaseOrderLineItem;
import com.scalar.chiptrack.finance.openpo.dao.PurchaseOrderDAO;

/**
 * Author: Phani Raja Kumar
 * Date: Feb 16, 2005
 * Time: 7:58:28 PM
 */
public class PurchaseOrderSaveCommand extends ChipTrackExtendedAction
{
    public ActionForward executeRequest( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)	throws ScalarException
    {
        HashMap errors			= new HashMap();
        HashMap info            = new HashMap();
        String actionForward 	= "saveSuccess";
        HttpSession mSession 	= request.getSession();
        PurchaseOrderForm purchaseOrderForm = ( PurchaseOrderForm ) form;
		OpenPurchaseOrderForm openPurchaseOrderForm = null;
        User user = (User)mSession.getAttribute( SessionKeys.USER_KEY );

        try
        {
           if ( isTokenValid ( request ) )
            {
                // Check wether the PO Number already Exists
                if( purchaseOrderForm.getPurchaseOrder_Id() == -1 && PurchaseOrderDAO.isPurchaseOrderNumberExists( purchaseOrderForm.getPurchaseOrderNumber() ) )
                {
                    if( purchaseOrderForm.getOpenPurchaseOrder_Id() == -1 )
                    {
                        purchaseOrderForm.setPurchaseOrderNumber( PurchaseOrderDAO.loadAutomatedPurchaseOrderNo () );
                    }

                    purchaseOrderForm.setBillingAddress( PurchaseOrderDAO.getClientAddress() );
                    purchaseOrderForm.setBillingAddress_id( PurchaseOrderDAO.getClientAddress().getAddressId() );

                    // If the Purchase Order Is created From an Open PO then Load the Shipping Address from Open PO
                    if( purchaseOrderForm.getOpenPurchaseOrder_Id() != -1 )
                    {
                        openPurchaseOrderForm = new OpenPurchaseOrderForm();
                        openPurchaseOrderForm.setPurchaseOrder_id( purchaseOrderForm.getOpenPurchaseOrder_Id() );

                        PurchaseOrderDAO.loadOpenPurchaseOrder( openPurchaseOrderForm );
                        purchaseOrderForm.setPurchaseOrderNumber( PurchaseOrderDAO.loadAutomatedPurchaseOrderNoByOpenPurchaseOrderNo( openPurchaseOrderForm ) );
                        purchaseOrderForm.setOpenPurchaseOrderNumber( openPurchaseOrderForm.getPoNumber() );
                        purchaseOrderForm.setVendorName( openPurchaseOrderForm.getVendorName() );
                        purchaseOrderForm.setShippingAddress_id( openPurchaseOrderForm.getShippingAddress_id() );
                        purchaseOrderForm.setShippingAddress( CustomerDAO.getAddress( purchaseOrderForm.getShippingAddress_id() ) );
                        purchaseOrderForm.setRemainingOpenPOAmt( openPurchaseOrderForm.getPoRemainingAmt() );
                        purchaseOrderForm.setValidToDate( openPurchaseOrderForm.getValidToDate() );
                    }
                    else
                    {
                        PurchaseOrderDAO.setVendorNameAndShippingAddresses( purchaseOrderForm );
                    }

                    Iterator lineItemIterator	= purchaseOrderForm.getPurchaseOrderLineItemList().iterator();
                    while ( lineItemIterator.hasNext() )
                    {
                        PurchaseOrderLineItem purchaseOrderLineItem = ( PurchaseOrderLineItem ) lineItemIterator.next();
                        purchaseOrderLineItem.setPartNumbersList( PurchaseOrderDAO.loadPartNumbersByVendorIdAndLocation( purchaseOrderForm.getVendor_id(), purchaseOrderLineItem.getProcessName() ) );
                    }

                    request.setAttribute( "purchaseOrderTypesList", PurchaseOrderDAO.loadPurchaseOrderTypes() );
                    request.setAttribute( "processNameList", PurchaseOrderDAO.loadProcessNames( purchaseOrderForm.getVendor_id() ) );
                    request.setAttribute( "packageTypeList", PurchaseOrderDAO.loadPackageTypeList() );
                    request.setAttribute( "financeReasonCodes", PurchaseOrderDAO.loadFinanceHolds() );
                    request.setAttribute( "opsReasonCodes", PurchaseOrderDAO.loadOperationsHolds()  );
                    request.setAttribute( "poTaxes", PurchaseOrderDAO.loadPOTaxesList () );

                    String searchType = request.getParameter("searchType");
                    request.setAttribute( "searchType", searchType);

                    info.put( "Purchase Order Number already exists. New Purchase Order number has been generated ", purchaseOrderForm.getPurchaseOrderNumber() );
                    actionForward = "NewManufacturingPO";
                }
                else
                {
                    if( purchaseOrderForm.getOpenPurchaseOrder_Id() != -1 )
                    {
                        openPurchaseOrderForm = new OpenPurchaseOrderForm();
                        openPurchaseOrderForm.setPurchaseOrder_id( purchaseOrderForm.getOpenPurchaseOrder_Id() );
                        PurchaseOrderDAO.loadOpenPurchaseOrder( openPurchaseOrderForm );
                        
                        if( purchaseOrderForm.getTotal() > (Double.parseDouble( openPurchaseOrderForm.getPoRemainingAmt()) + purchaseOrderForm.getTotalAsInDatabase() ) )
                        {
                            if( purchaseOrderForm.getOpenPurchaseOrder_Id() != -1 )
                            {
                                PurchaseOrderDAO.loadOpenPurchaseOrder( openPurchaseOrderForm );
                                purchaseOrderForm.setOpenPurchaseOrderNumber( openPurchaseOrderForm.getPoNumber() );
                                purchaseOrderForm.setVendorName( openPurchaseOrderForm.getVendorName() );
                                purchaseOrderForm.setShippingAddress_id( openPurchaseOrderForm.getShippingAddress_id() );
                                purchaseOrderForm.setShippingAddress( CustomerDAO.getAddress( purchaseOrderForm.getShippingAddress_id() ) );
                                purchaseOrderForm.setRemainingOpenPOAmt( openPurchaseOrderForm.getPoRemainingAmt() );
                                purchaseOrderForm.setValidToDate(openPurchaseOrderForm.getValidToDate() );
                            }
                            else
                            {
                                PurchaseOrderDAO.setVendorNameAndShippingAddresses( purchaseOrderForm );
                            }

                            Iterator lineItemIterator	= purchaseOrderForm.getPurchaseOrderLineItemList().iterator();
                            while ( lineItemIterator.hasNext() )
                            {
                                PurchaseOrderLineItem purchaseOrderLineItem = ( PurchaseOrderLineItem ) lineItemIterator.next();
                                purchaseOrderLineItem.setPartNumbersList( PurchaseOrderDAO.loadPartNumbersByVendorIdAndLocation( purchaseOrderForm.getVendor_id(), purchaseOrderLineItem.getProcessName() ) );
                            }

                            request.setAttribute( "purchaseOrderTypesList", PurchaseOrderDAO.loadPurchaseOrderTypes() );
                            request.setAttribute( "processNameList", PurchaseOrderDAO.loadProcessNames( purchaseOrderForm.getVendor_id() ) );
                            request.setAttribute( "packageTypeList", PurchaseOrderDAO.loadPackageTypeList() );
                            request.setAttribute( "financeReasonCodes", PurchaseOrderDAO.loadFinanceHolds() );
                            request.setAttribute( "opsReasonCodes", PurchaseOrderDAO.loadOperationsHolds()  );
                            request.setAttribute( "poTaxes", PurchaseOrderDAO.loadPOTaxesList () );

                            //added by Murali Krishna on 21st march 2005
                            String searchType = request.getParameter("searchType");
                            request.setAttribute( "searchType", searchType);

                            actionForward = "NewManufacturingPO";

                            errors.put( "Purchase Order total exceeds the Open Purchase Order Remaining Amount ", null );
                        }
                    }

                    if( errors == null || errors.isEmpty() == true )
                    {
                        double subTotal  = purchaseOrderForm.getSubTotal();

                        if( subTotal == 0.0 )
                        {
                            purchaseOrderForm.setTradeDiscount( 0.0 );
                            purchaseOrderForm.setFreight( 0.0 );
                            purchaseOrderForm.setMiscellaneous( 0.0 );
                            purchaseOrderForm.setTotal( 0.0 );
                        }

                        PurchaseOrderDAO.savePurchaseOrder( purchaseOrderForm, user.getUserId() );

                        //added by Murali Krishna
                        mSession.removeAttribute("purchaseOrderForm");

                        actionForward = "Generate";
                        PurchaseOrderReceiptForm purchaseOrderReceiptForm = PurchaseOrderConfirmCommand.preparePurchaseOrderReceipt( purchaseOrderForm );

                        if( purchaseOrderReceiptForm != null )
                        {
                            PurchaseOrderDAO.savePurchaseOrderReceipt( purchaseOrderReceiptForm, user.getFirstName() );
                            Logger.info( INFO_PURCHASE_ORDER_RECEIPT_SAVED_SUCCEFULLY );
                            info.put( purchaseOrderReceiptForm.getReceipt_Number(), INFO_PURCHASE_ORDER_RECEIPT_SAVED_SUCCEFULLY );
                            info.put( "View/Print", "Click here to <a href='javascript:showForReceipt("+purchaseOrderReceiptForm.getReceipt_id()+");' onmouseover=\"window.status='Click here to View/print purchase order receipt';return true\" onmouseout=\"window.status='';return true\"> view/print </a>Purchase Order Receipt Details");
                        }
                        resetToken ( request );

                        String searchType = ( String ) request.getParameter("searchType");
                        if( searchType == null || "".equals( searchType ) )
                        {
                            searchType = "OpenPOSearch";
                        }

                        if( searchType != null )
                        {
                            actionForward = searchType;
                            request.setAttribute( "vendorsList", PurchaseOrderDAO.loadAllVendors() );
                            request.setAttribute( "yearList", PurchaseOrderDAO.getYearList () );
                            request.setAttribute( "purchaseOrderTypesList", PurchaseOrderDAO.loadPurchaseOrderTypes() );
                            request.setAttribute( "purchaseOrderStatusList", PurchaseOrderDAO.loadPurchaseOrderStatusTypes( false) );
                            request.setAttribute( "productList", PurchaseOrderDAO.loadPOProductsList() );
                            request.setAttribute ( "years", PurchaseOrderDAO.getYearList () );
                            request.setAttribute( "action", searchType );
                        }
                        else
                        {
                            request.setAttribute( "vendorsList", PurchaseOrderDAO.loadPOVendors() );
                            request.setAttribute( "purchaseOrderTypesList", PurchaseOrderDAO.loadPurchaseOrderTypes() );
                        }

                        Logger.info( INFO_PURCHASE_ORDER_INFORMATION_SAVED_SUCCESSFULLY );
                        info.put( purchaseOrderForm.getPurchaseOrderNumber(), INFO_PURCHASE_ORDER_INFORMATION_SAVED_SUCCESSFULLY );
                        info.put( "View/Print ", "Click here to <a href='javascript:showStaPoForViewPrint(" + purchaseOrderForm.getPurchaseOrder_Id() + ", "+ purchaseOrderForm.getVendor_id() +");' onmouseover=\"window.status='Click here to View/print purchase order';return true\" onmouseout=\"window.status='';return true\"> view/print </a>Purchase Order Details" );
                        mSession.removeAttribute( "purchaseOrderForm" );
                        mSession.removeAttribute( "purchaseOrderReceiptForm" );
                    }
                }
           }
           else
           {
               errors.put ( ERROR_PURCHASE_ORDER_ALREADY_SAVED, null );
               String searchType = ( String ) request.getParameter("searchType");
               if( searchType == null || "".equals( searchType ) )
               {
                   searchType = "OpenPOSearch";
               }

               if( searchType != null )
               {
                   actionForward = searchType;
                   request.setAttribute( "vendorsList", PurchaseOrderDAO.loadAllVendors() );
                   request.setAttribute( "yearList", PurchaseOrderDAO.getYearList () );
                   request.setAttribute( "purchaseOrderTypesList", PurchaseOrderDAO.loadPurchaseOrderTypes() );
                   request.setAttribute( "purchaseOrderStatusList", PurchaseOrderDAO.loadPurchaseOrderStatusTypes( false) );
                   request.setAttribute( "productList", PurchaseOrderDAO.loadPOProductsList() );
                   request.setAttribute ( "years", PurchaseOrderDAO.getYearList () );
                   request.setAttribute( "action", searchType );
               }
               else
               {
                   request.setAttribute( "vendorsList", PurchaseOrderDAO.loadPOVendors() );
                   request.setAttribute( "purchaseOrderTypesList", PurchaseOrderDAO.loadPurchaseOrderTypes() );
               }
           }

        }
        catch ( Exception e )
        {
            e.printStackTrace();
            Logger.error( ERROR_SAVING_PURCHASE_ORDER_INFORMATION, e );
            errors.put( ERROR_INTERNAL_SERVER_ERROR, "" );
            mSession.setAttribute( ERROR_REPORT_OBJECT, new ErrorReport( "Error while executing the command", e ) );
			request.setAttribute( "vendorsList", PurchaseOrderDAO.loadPOVendors() );
			request.setAttribute( "purchaseOrderTypesList", PurchaseOrderDAO.loadPurchaseOrderTypes() );
            actionForward = "Generate";
        }

        request.setAttribute( ERROR_MESSAGES, errors );
        request.setAttribute( INFO_MESSAGES, info );
        return mapping.findForward( actionForward );
    }

}

